package com.example.demo.OtherCoding;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-05-14
 * Time: 13:58
 */
public class Code_calculate {
    class Solution {
        public int calculate(String s) {
            int num = 0;
            char sign = '+';
            Stack<Integer> stack = new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (Character.isDigit(c)) {
                    num = num * 10 + (c - '0');
                } else if (c == '(') {//处理括号
                    int n = 1;
                    i++;
                    StringBuilder sb = new StringBuilder();
                    while (i < s.length() && (s.charAt(i) != ')' || n != 1)) {// 处理多重括号
                        sb.append(s.charAt(i));
                        if (s.charAt(i) == '(') n++;
                        else if (s.charAt(i) == ')') n--;
                        i++;
                    }
                    num = calculate(sb.toString());//括号中的表达式的值
                }
                if (!Character.isDigit(c) && c != ' ' || s.length() - 1 == i) {
                    switch (sign) {
                        case '+':
                            stack.push(num);
                            break;
                        case '-':
                            stack.push(-num);
                            break;
                        case '*':
                            stack.push(num * stack.pop());
                            break;
                        case '/':
                            stack.push(stack.pop() / num);
                            break;
                    }
                    sign = c;
                    num = 0;
                }
            }
            int res = 0;
            while (!stack.isEmpty()) {
                res += stack.pop();
            }
            return res;
        }
    }
}
